package com.atguigu.tingshu.album.api;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.common.result.Result;
import io.minio.*;
import io.minio.errors.MinioException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Tag(name = "上传管理接口")
@RestController
@RequestMapping("api/album")
@EnableConfigurationProperties(MinioConstantProperties.class)
@RefreshScope
public class FileUploadApiController {

    @Autowired
    private MinioConstantProperties minioConstantProperties;

    //file这个形参名不能改,因为前端写死了
    @Operation(summary = "文件上传")
    @PostMapping("/fileUpload")
    public Result fileUpload(@RequestParam MultipartFile file) throws Exception {

        // minio客户端
        MinioClient minioClient =
            MinioClient.builder()
                .endpoint(minioConstantProperties.getEndpointUrl())
                .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecreKey())
                .build();

        // 创建桶
        String bucketName = minioConstantProperties.getBucketName();
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!found) {
            // Make a new bucket called 'asiatrip'.
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        } else {
            System.out.println("Bucket '"+ bucketName +"' already exists.");
        }

/*      //不上传本地图片,上传请求中的网络图片
        // Upload '/home/user/Photos/asiaphotos.zip' as object name 'asiaphotos-2015.zip' to bucket
        // 'asiatrip'.
        minioClient.uploadObject(
            UploadObjectArgs.builder()
                .bucket(bucketName)
                .object("asiaphotos-2015.zip")
                .filename("/home/user/Photos/asiaphotos.zip")
                .build());

        System.out.println(
            "'/home/user/Photos/asiaphotos.zip' is successfully uploaded as "
                + "object 'asiaphotos-2015.zip' to bucket 'asiatrip'.");
*/
        //拼接文件名
        String fileName = new SimpleDateFormat("yyyyMMdd/HH").format(new Date()) + "/"
                + UUID.randomUUID().toString().replaceAll("-","")
                + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        //上传到MinIO服务器
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)//设置图片上传到哪个bucket中
                .object(fileName)//设置图片在MinIO中的名字
                //stream三个参数:
                // 文件的输入流
                // 文件字节大小
                // 文件拆分方式(-1表示由minio自动拆分,0表示不拆分,也可以指定拆分大小)
                .stream(file.getInputStream(), file.getSize(), -1)//将图片转成流进行上传
                .contentType(file.getContentType())
                .build());//获取文件的MIME类型,并添加到MinIO中

        //拼接url,拼接返回的地址是永久的,9001端口管理端share的是临时的(去掉url后面的参数变成永久)
        String url = String.join("/", minioConstantProperties.getEndpointUrl(), bucketName, fileName);

        System.out.println("file.getOriginalFilename() = " + file.getOriginalFilename());
        System.out.println("fileName = " + fileName);
        System.out.println("url = " + url);

        return Result.ok(url);

    }



}
